package com.leetcode.demo05;

public class Solution {
    /*public String longestPalindrome(String s) {
        String ans = "" ;  //定义最后返回的结果
        int max = 0; //用来保存当前最长的回文串的长度
        int len = s.length();
        for (int i = 0; i < len; i++) {
            for (int j = i+1 ; j <=len ; j++) {
                String test = s.substring(i, j);
                if (isPalindrome(test) && test.length()>max) {
                    ans = test;
                    max = Math.max(max , ans.length());
                }
            }
        }
        return ans;
    }

    public boolean isPalindrome(String s) {
        int len = s.length();
        for (int i = 0; i < len/2 ; i++) {
            if (s.charAt(i) != s.charAt(len-i-1)) {
                return false;
            }
        }
        return true;
    }*/

    /*public String longestPalindrome (String s) {
        //判断特殊情况，如果为空
        if (s.equals("")) {
            return "";
        }
        String orgin = s;
        String reverse = new StringBuffer(s).reverse().toString();  //转置原本字符串
        int length = s.length();
        int [][] arr = new int[length][length] ;
        int maxLen = 0 , maxEnd = 0;

        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length; j++) {
                if (orgin.charAt(i) == reverse.charAt(j)) {
                    //是否在边缘位置
                    if (i ==0 || j == 0 ) {
                        arr[i][j] = 1;
                    } else {
                        arr[i][j] = arr[i-1][j-1] + 1;
                    }
                }
                if (arr[i][j] > maxLen) {
                    int before = length-1 -j;
                    if(before+arr[i][j]-1 == i){
                        maxLen = arr[i][j];
                        maxEnd = i;
                    }

                }

            }
        }
        return s.substring(maxEnd-maxLen+1,maxEnd+1);
    }*/


    public String longestPalindrome(String s) {
        int length = s.length();
        boolean[][] p = new boolean[length][length];
        int maxLen = 0;
        String maxPal = "";
        for (int len = 1; len < length; len++) {
            for (int start = 0; start < length; start++) {
                int end = start +len -1;
                if (end >= length) {
                    break;
                }
                p[start][end] = ( len==1  || len==2 || p[start+1][end-1] )   &&   (s.charAt(start) == s.charAt(end));

                if(p[start][end] && len >maxLen ) {
                    maxPal = s.substring(start,end+1);
                }

            }
        }
        return maxPal;
    }





}
